package io.renren.modules.test.library.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.modules.product.service.ProductService;
import io.renren.modules.product.service.ProductUserService;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.test.library.entity.Library;
import io.renren.modules.test.library.mapper.LibraryMapper;
import io.renren.modules.test.library.service.LibraryService;
import io.renren.modules.test.usecase.entity.UseCase;
import io.renren.modules.test.usecase.entity.UseCaseLibrary;
import io.renren.modules.test.usecase.service.CaseLibraryService;
import io.renren.modules.test.usecase.service.CaseService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liyinuo
 * 测试库基本操作实现
 */
@Service
public class LibraryServiceImpl extends ServiceImpl<LibraryMapper, Library> implements LibraryService {
    @Autowired
    CaseService caseService;
    @Autowired
    CaseLibraryService caseLibraryService;
    @Autowired
    ProductService productService;
    @Autowired
    ProductUserService productUserService;

    @Override
    public void removeLibrary(Long id) {
        removeById(id);
        List<UseCaseLibrary> list = caseLibraryService.list(new QueryWrapper<UseCaseLibrary>().eq("library_id", id));
        for (UseCaseLibrary useCaseLibrary : list) {
            caseService.remove(new QueryWrapper<UseCase>().eq("case_id",useCaseLibrary.getCaseId()));
        }
        caseLibraryService.remove(new QueryWrapper<UseCaseLibrary>().eq("library_id",id));
    }

    @Override
    public IPage<Library> getListLibrary(Integer pageNo, Integer pageSize, String libraryName) {
        Page<Library> page = new Page<>(pageNo, pageSize);
        IPage<Library> pageList = this.page(page, new QueryWrapper<Library>().likeRight("library_name",libraryName));
        List<Library> records = pageList.getRecords();
        //根据用户参与了哪些产品就显示哪些测试库
        //1、根据当前用户用户id获取用户参与了哪些产品并获取到这些产品id
        List<Long> productIds = productUserService.getProductIdsByUserId();
        //2、根据这些产品id过滤测试库
        List<Library> newRecords = records.stream()
                .filter(item -> productIds.contains(item.getProductId()))
                .map(library -> {
                    library.setProductName(productService.getById(library.getProductId()).getProductName());
                    return library;
                })
                .collect(Collectors.toList());
        pageList.setRecords(newRecords);
        pageList.setTotal(newRecords.size());
        return pageList;

    }
}
